package com.winning.sx.microframework.common.config;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.winning.sx.microframework.common.interceptor.ReqInterceptor;

import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.*;

import java.io.IOException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.TimeZone;

/**
 * 实现WebMvcConfigurer接口
 */
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

	/**
	 * 添加类型转换器和格式化器
	 *
	 * @param registry
	 */
	@Override
	public void addFormatters(FormatterRegistry registry) {
//        registry.addFormatterForFieldType(LocalDate.class, new USLocalDateFormatter());
	}

	/**
	 * 跨域支持
	 *
	 * @param registry
	 */
	@Override
	public void addCorsMappings(CorsRegistry registry) {
		registry.addMapping("/**")
				.allowedOrigins("*")
				.allowCredentials(true)
				.allowedMethods("GET", "POST", "DELETE", "PUT")
				.maxAge(3600 * 24);
	}

	/**
	 * 添加静态资源--过滤swagger-genericapi (开源的在线API文档)
	 *
	 * @param registry
	 */
	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		//过滤swagger
//        registry.addResourceHandler("swagger-ui.html")
//                .addResourceLocations("classpath:/META-INF/resources/");
//
//        registry.addResourceHandler("/webjars/**")
//                .addResourceLocations("classpath:/META-INF/resources/webjars/");
//
//        registry.addResourceHandler("/swagger-resources/**")
//                .addResourceLocations("classpath:/META-INF/resources/swagger-resources/");
//
//        registry.addResourceHandler("/swagger/**")
//                .addResourceLocations("classpath:/META-INF/resources/swagger*");
//
//        registry.addResourceHandler("/v2/genericapi-docs/**")
//                .addResourceLocations("classpath:/META-INF/resources/v2/genericapi-docs/");


//		registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
//		registry.addResourceHandler("/html/**").addResourceLocations("classpath:/html/");
		registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
		registry.addResourceHandler("/assets/**").addResourceLocations("classpath:/assets/");

	}

	@Override
	public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
	}

	/**
	 * 注册拦截器
	 */
	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		//拦截的请求用addPathPatterns，排除的请求用excludePathPatterns("/a.do")
//		registry.addInterceptor(new TokenInterceptor()).addPathPatterns("/webAPI/**");
		registry.addInterceptor(new ReqInterceptor()).addPathPatterns("/**");
	}

	@Override
	public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
		converters.stream().filter(c -> c instanceof MappingJackson2HttpMessageConverter).forEach(cvt -> {
			MappingJackson2HttpMessageConverter converter = (MappingJackson2HttpMessageConverter) cvt;
			ObjectMapper objectMapper = converter.getObjectMapper();
			//添加Timestamp序列化器
			SimpleModule simpleModule = new SimpleModule();
			simpleModule.addSerializer(Timestamp.class, CustomDateSerializer.instance());
			simpleModule.addSerializer(Integer.class, IntSerializer.instance());
			objectMapper.registerModule(simpleModule);
			objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
				@Override
				public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
					//如果需要将null值输出为“”，取消这里的注释。
					jsonGenerator.writeString("");
				}
			});
			String dateFormat = "yyyy-MM-dd HH:mm:ss";
			objectMapper.setDateFormat(new SimpleDateFormat(dateFormat));
			objectMapper.setTimeZone(TimeZone.getDefault());
		});
	}

}